//
//  FDAuthorization.m
//  FD
//
//  Created by Yasin on 2018/10/13.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//

#import "FDAuthorization.h"
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>

//分类
#import "NSString+Extension.h" //base64编码
#import "NSData+hex.h" //NSData 的内容原封不动的转换为 NSString

@implementation FDAuthorization

#pragma mark - 生成Authorization

+ (NSString *)authorizationWithToken:(NSString *)token apiStr:(NSString *)api timeStamp:(NSString *)timeStamp {
    
    //根据时间戳 生成签名
    NSString *signatureStr = [self signatureWithAPI:api timeStamp:timeStamp];
    //拼接
    NSString *autho = [NSString stringWithFormat:@"%@:%@",token,signatureStr];

    //base 编码 后返回。
    return [autho rb_base64EncodingString];
}

#pragma mark - 签名
+ (NSString *)signatureWithAPI:(NSString *)api timeStamp:(NSString *)timeStamp{
    NSString *device = @"ios";
    
    NSString *version = @"1.0.0";
    
    //拼接 device + timeStamp+ version
    NSString *dtvValue = [NSString stringWithFormat:@"%@\n%@\n%@",device,timeStamp,version];
    
    //签名
    NSString *signagure = [self HmacSha1:api data:dtvValue];
//    NSLog(@"3333:%@",signagure);
    return signagure;
}

#pragma mark - 工具方法
//!!!!: 2. HmacSHA1加密；
+ (NSString *)HmacSha1:(NSString *)key data:(NSString *)value
{
    NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
    NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
    
    unsigned char result[CC_SHA1_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA1, [keyData bytes], [keyData length], [valueData bytes], [valueData length], result);
    
    NSData *HMAC = [[NSData alloc] initWithBytes:result
                                          length:sizeof(result)];
//    NSLog(@"%d行  %@",__LINE__,HMAC);
    NSString *str =  [HMAC convertDataToHexStr:HMAC];
//    NSLog(@"%d行  %@",__LINE__,str);
    
    return str;
}
@end
